#include "logincode.h"
#include <QEvent>
#include <QFrame>
#include <QGraphicsDropShadowEffect>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainterPath>
#include <QPushButton>
#include <QVBoxLayout>
#include "utils/signalcenter.h"
#include "utils/util.h"
loginCode::loginCode(QWidget *parent)
    : QDialog(parent)
    , mainVLayout(new QVBoxLayout(this))
    , setBarHLayoout(new QHBoxLayout())
    , btnSet(new QPushButton())
    , label_logo(new QLabel())
    , logoHLayout(new QHBoxLayout())
    , btnweChatLogin(new QPushButton())
    , btnJoin(new QPushButton())
    , toolBtnPhone(new QToolButton())
    , toolBtnEmail(new QToolButton())
    , toolBtnPasswd(new QToolButton())
{
    //mainVLayout->setSpacing(6);
    mainVLayout->setObjectName("QVBoxLayout");
    mainVLayout->setContentsMargins(
        0, 0, 0, 0); //这是设置内边距的，及布局到窗口的距离，可以控制垂直布局的左上右下离窗口的边界

    //这是最顶层上面上个的按钮的布局设置，水平布局

    /*  这是最顶层一栏的组件  */
    //设置按钮
    setBarHLayoout->setObjectName("setBarHLayoout");
    setBarHLayoout->setAlignment(Qt::AlignLeft);
    setPushBtn(btnSet,
               "btnSet",
               QSize(32, 32),
               "",
               "QPushButton{border:none}",
               true,
               ":/resources/set1.png");
    //btnSet->installEventFilter(this);
    addButtonIconMapping(btnSet, ":/resources/set2.png", ":/resources/set1.png");
    setBarHLayoout->addWidget(btnSet);

    //下面这个则是显示软件logo的label

    mainVLayout->addLayout(setBarHLayoout);

    //设置间距
    mainVLayout->setSpacing(10);

    // logoHLayout->setSpacing(6);
    logoHLayout->setObjectName("logoHLayout");

    label_logo->setObjectName("label_log");
    label_logo->setMinimumSize(QSize(400, 336));
    label_logo->setMaximumSize(QSize(400, 336));
    label_logo->clear();
    QPixmap *pix = new QPixmap(":/resources/log.png");
    //设置按照label_log的大小进行缩放，保持宽高比例
    pix->scaled(label_logo->size(), Qt::KeepAspectRatio);
    //设置图片按照标签的大小自动缩放，即跟随缩放
    label_logo->setScaledContents(true);
    label_logo->setPixmap(*pix);
    logoHLayout->addWidget(label_logo);
    mainVLayout->addLayout(logoHLayout);

    //添加上一个组件和下一个组件的间距
    mainVLayout->setSpacing(10);

    //添加一个垂直布局
    QVBoxLayout *verticalLayout = new QVBoxLayout();
    verticalLayout->setObjectName("verticalLayout");

    setPushBtn(btnweChatLogin,
               "btnweChatLogin",
               QSize(400, 50),
               "",
               "border: none;",
               true,
               ":/resources/wechatLogin.png");
    //将图标加入到垂直布局中
    verticalLayout->addWidget(btnweChatLogin);
    addButtonIconMapping(btnweChatLogin,
                         ":/resources/wechatLogin2.png",
                         ":/resources/wechatLogin.png");

    verticalLayout->setSpacing(6);

    //加入按钮的设置
    setPushBtn(btnJoin, "btnJoin", QSize(400, 50), "", "border: none;", true, ":/resources/join.png");
    verticalLayout->addWidget(btnJoin);
    addButtonIconMapping(btnJoin, ":/resources/join2.png", ":/resources/join.png");
    mainVLayout->addLayout(verticalLayout);

    //添加一个水平布局用来放置分割线
    QHBoxLayout *HBoxLayout2 = new QHBoxLayout();
    HBoxLayout2->setSpacing(6);
    HBoxLayout2->setObjectName("HBoxLayout2");

    //使用QFrame来充当水平分割线
    QFrame *line1 = new QFrame(this);
    line1->setObjectName("line1");
    line1->setFrameShape(QFrame::HLine);
    line1->setFrameShadow(QFrame::Sunken);

    HBoxLayout2->addWidget(line1);

    QLabel *label2 = new QLabel();
    label2->setObjectName("label2");
    label2->setAlignment(Qt::AlignCenter);
    label2->setText("其它登录方式");
    label2->setStyleSheet("color: rgb(80, 80, 80);");
    QFont font2 = label2->font();
    font2.setFamily("Microsoft YaHei");
    font2.setPointSize(10);
    font2.setWeight(QFont::Medium);
    HBoxLayout2->addWidget(label2);

    QFrame *line2 = new QFrame(this);
    line2->setObjectName("line2");
    line2->setFrameShape(QFrame::HLine);
    line2->setFrameShadow(QFrame::Sunken);

    HBoxLayout2->addWidget(line2);
    mainVLayout->addLayout(HBoxLayout2);

    //设置窗口颜色为白色
    this->setStyleSheet("background-color: white;");

    QHBoxLayout *HBoxLayout3 = new QHBoxLayout();
    HBoxLayout3->setObjectName("HBoxLayout3");
    HBoxLayout3->setSpacing(6);

    setToolBtn(toolBtnPhone,
               "toolBtnPhone",
               QSize(60, 80),
               "手机号",
               Qt::ToolButtonTextUnderIcon,
               "background-color:white;border:none;color: rgb(80, 80, 80);",
               true,
               ":/resources/phonelogin.png");
    addButtonIconMapping(toolBtnPhone, ":/resources/phonelogin2.png", ":/resources/phonelogin.png");
    HBoxLayout3->addWidget(toolBtnPhone);

    //接下来是密码
    setToolBtn(toolBtnPasswd,
               "toolBtnPasswd",
               QSize(60, 80),
               "账户密码",
               Qt::ToolButtonTextUnderIcon,
               "background-color:white;border:none;color: rgb(80, 80, 80);",
               true,
               ":/resources/passwd1.png");
    addButtonIconMapping(toolBtnPasswd, ":/resources/passwd2.png", ":/resources/passwd1.png");
    HBoxLayout3->addWidget(toolBtnPasswd);

    //接下来是邮箱

    setToolBtn(toolBtnEmail,
               "toolBtnEmail",
               QSize(60, 80),
               "邮箱",
               Qt::ToolButtonTextUnderIcon,
               "background-color:white;border:none;color: rgb(80, 80, 80);",
               true,
               ":/resources/email1.png");
    addButtonIconMapping(toolBtnEmail, ":/resources/email2.png", ":/resources/email1.png");
    HBoxLayout3->addWidget(toolBtnEmail);

    mainVLayout->addLayout(HBoxLayout3);

    QHBoxLayout *spaceHBoxLayout = new QHBoxLayout();
    QLabel *spacerLabel = new QLabel();
    spacerLabel->setMinimumSize(QSize(400, 50));
    spacerLabel->setMaximumSize(QSize(400, 50));
    spacerLabel->setText("");
    spaceHBoxLayout->addWidget(spacerLabel);

    mainVLayout->addLayout(spaceHBoxLayout);

    this->setWindowTitle("AiKe Metting");
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinMaxButtonsHint);
    connect(btnSet, &QPushButton::clicked, this, &loginCode::onBtnSetClicked);
    connect(&SIGNALCENTER, &SignalCenter::closeWidget, this, &loginCode::onCloseWidget);
    connect(toolBtnPhone, &QToolButton::clicked, this, &loginCode::onBtnPhoneClicked);
    setWindowFlags(Qt::FramelessWindowHint);
    // 设置窗口透明用来支持圆角样式属性
    setAttribute(Qt::WA_TranslucentBackground);
}

void loginCode::onBtnSetClicked()
{
    if (!settingPtr) {
        settingPtr.reset(new settingWidget());
        //生成了settingWidget后，再进行连接
        connect(settingPtr.get(), &settingWidget::clearSetting, this, [&]() {
            settingPtr.reset();
            qDebug() << "238: setting已释放";
        });
    }
    settingPtr->show();
}

void loginCode::onCloseWidget()
{
    if (settingPtr) {
        settingPtr->close();
    }
}

void loginCode::onBtnPhoneClicked()
{
    SIGNALCENTER.toolBtnPhoneClicked();
}

void loginCode::setToolBtn(QToolButton *btn,
                           const QString &objectName,
                           const QSize &size,
                           const QString &text,
                           Qt::ToolButtonStyle style,
                           const QString &styleSheet,
                           bool useIcon,
                           const QString &iconURL,
                           const uint8_t width,
                           const uint8_t heigth)
{
    btn->setObjectName(objectName);
    btn->setMinimumSize(size);
    btn->setMaximumSize(size);
    btn->setText(text);
    if (useIcon) {
        btn->setIcon(QIcon(iconURL));
        if (width == 0 && heigth == 0) {
            btn->setIconSize(btn->size());
        } else {
            btn->setIconSize(QSize(width, heigth));
        }
    }

    btn->setToolButtonStyle(style);
    btn->setStyleSheet(styleSheet);
}

void loginCode::changeIcon(QAbstractButton *btn, const QString &iconURL)
{
    QIcon icon(iconURL);
    btn->setIcon(icon);
    btn->setIconSize(btn->size());
}

void loginCode::addButtonIconMapping(QAbstractButton *button,
                                     const QString &iconEnter,
                                     const QString &iconLevel)
{
    if (button) {
        buttonIconMap.insert(button, QPair<QString, QString>(iconEnter, iconLevel));
        button->installEventFilter(this);
    }
}

// /**
//  * @brief loginCode::mousePressEvent  这个函数就是计算点击时鼠标相对于窗口左上角的位置
//  * @param event
//  */
// void loginCode::mousePressEvent(QMouseEvent *event)
// {
//     if (event->button() == Qt::LeftButton) {
//         m_dragging = true;
//         m_offset = event->globalPosition().toPoint() - frameGeometry().topLeft();
//         event->accept();
//     }
// }

// void loginCode::mouseMoveEvent(QMouseEvent *event)
// {
//     if (m_dragging) {
//         move(QPoint(static_cast<int>(event->globalPosition().x() - m_offset.x()),
//                     static_cast<int>(event->globalPosition().y() - m_offset.y())));
//         event->accept();
//     }
// }

// void loginCode::mouseReleaseEvent(QMouseEvent *event)
// {
//     if (event->button() == Qt::LeftButton) {
//         m_dragging = false;
//         event->accept();
//     }
// }

// /**
//  * @brief loginCode::paintEvent  重写窗口的paintEvent事件处理函数，该函数的作用就是绘制窗口的背景和边框，因为我们已经将背景设置为透明了，因此我们需要
//  * 重新绘制，setBrush画刷，主要用来设置填充的背景的颜色的，setPen主要用来设置绘制的线条的，比如边框。
//  * @param event
//  */
// void loginCode::paintEvent(QPaintEvent *event)
// {
//     //该类设置成绘制对象
//     QPainter painter(this);

//     //设置渲染属性，QPainter::Antialiasing：表示如果可能，引擎应该对图元的边缘进行抗锯齿处理
//     //setRenderHint主要用于优化绘图，可以设置抗锯齿，和光滑的像素图转换和高质量的抗锯齿
//     painter.setRenderHint(QPainter::Antialiasing);

//     //设置画刷
//     painter.setBrush(QColor(255, 255, 255));

//     //设置画笔，用来画边框,透明
//     painter.setPen(Qt::gray);

//     //获取窗口的矩形区域
//     QRect rect = this->rect();

//     painter.drawRoundedRect(rect, 10, 10);
//     QWidget::paintEvent(event);
// }

/**
 * @brief loginCode::eventFilter   这是事件过滤器，用于处理对象所发生的事件
 * @param watch  这是需要监听的对象
 * @param event   这是对象发生的事件
 * @return 
 */
bool loginCode::eventFilter(QObject *watch, QEvent *event)
{
    QAbstractButton *button = qobject_cast<QAbstractButton *>(watch);
    if (button && buttonIconMap.contains(button)) {
        const QPair<QString, QString> &icons = buttonIconMap.value(button);
        if (event->type() == QEvent::Enter)
            changeIcon(button, icons.first);
        else if (event->type() == QEvent::Leave)
            changeIcon(button, icons.second);
    }
    return QObject::eventFilter(watch, event);
}
